package com.dycong.common.IO.socket.SSL.ssl;

import javax.net.ssl.*;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Properties;

/**
 * Created by dycong on 2017/3/28.
 */
public class ClientAuth {
    private static SSLContext sslContext;

    public static SSLContext getSslContext() throws Exception {
        //todo keyManagers key 授权的密钥管理器，用来授权验证，验证服务端身份
        Properties properties = Configuration.getConfig();
        String keystorePath = properties.getProperty("clientKeystore");
        char[] keyStorePw = properties.getProperty("keyStorePw").toCharArray();
        char[] PASSWORD = properties.getProperty("PASSWORD").toCharArray();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(keystorePath), keyStorePw);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(keyStore, PASSWORD);
        KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

        //todo TrustKeyStore 身份认证，第二个是被授权的证书管理器，向服务端证明自己的身份
        String TrustCerFile = properties.getProperty("clientTrustCer");
        char[] TrustCerPwd = properties.getProperty("clientTrustCerPwd").toCharArray();
        KeyStore trustKeyStore = KeyStore.getInstance("JKS");
        trustKeyStore.load(new FileInputStream(TrustCerFile), TrustCerPwd);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        //sslContext
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keyManagers, trustManagers, new SecureRandom());
        return sslContext;
    }
}
